import axios from 'axios';
import { createUid } from '@dms/utils';
import { pathToRegexp } from 'path-to-regexp';
import serviceDict from '@dms/apis/src/service';
import { getFullURL } from '@/utils';
// import { dms } from '@dms/apis';
import uniStore from '@/utils/uniStore';

// 服务端返回的错误code 白名单接口，白名单接口出现异常时需要自行接口异常code
const responseWhiteList = [];

function clearLogout(errorMsg) {
  if (errorMsg) {
    uni.showToast({
      title: errorMsg,
      icon: 'error',
      duration: 3000,
    });
  }
  uni.reLaunch({
    url: '/pages/login/index',
  });
}

// 创建axios实例
export const service = axios.create({
  timeout: 60000, // 请求超时时间
  baseURL: serviceDict.apiService[import.meta.env.VITE_APP_SERVER],

  adapter(config) {
    // console.log(config)
    const { url, method, data, params, headers, baseURL, paramsSerializer } =
      config;
    return new Promise((resolve, reject) => {
      uni.request({
        method: method.toUpperCase(),
        url: getFullURL(baseURL || '', url, params, paramsSerializer),
        header: headers,
        data,
        dataType: 'json',
        responseType: config.responseType,
        success: (res) => {
          resolve({
            ...res,
            config,
          });
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  },
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['X-Requested-With'] = 'XMLHttpRequest';
    config.headers['clientType'] = '3';
    config.headers['platformType'] = '1';
    config.headers['requestId'] = createUid();
    // config.headers['X-Platform'] = 'govAdmin';
    const accessToken = uniStore.getStoreItem('account', 'accessToken');
    if (accessToken) {
      config.headers.accessToken = accessToken;
    }
    return config;
  },
  (error) => ({ status: 0, msg: error.message }),
);

let errorLock = false;
// response拦截器
service.interceptors.response.use(
  async (response) => {
    // console.log('response', response);
    const res = response;
    let isWhite = false;
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    for (const api of responseWhiteList.values()) {
      if (
        pathToRegexp(api, [], {
          start: true,
          end: false,
        }).test(res.config.url)
      ) {
        isWhite = true;
        break;
      }
    }
    // isWhite = true; 由前端自定义提示
    if (res.statusCode === 200 && !isWhite) {
      switch (res.data.respCode) {
        case 0:
          errorLock = false;
          return res.data;
        case 300:
        case 404:
        case 417: // 系统内部错误
        case 500:
        case 600:
        case 10200: // 图形验证码失效
          uni.showToast({
            title: res.data.respDesc,
            icon: 'error',
            duration: 3000,
          });
          break;
        case 400:
          if (!errorLock) {
            errorLock = true;
            if (
              !pathToRegexp('pages/login/index', [], {
                start: true,
                end: false,
              }).test(currentPage.route)
            ) {
              // token无效
              clearLogout(res.data.respDesc);
            }
          }
          break;
        case 401:
          // 无权限访问
          if (
            !pathToRegexp('pages/noAccess/index', [], {
              start: true,
              end: false,
            }).test(currentPage.route)
          ) {
            uni.reLaunch({
              url: '/pages/noAccess/index',
            });
          }
          break;
        case 402:
          if (
            !pathToRegexp('pages/login/index', [], {
              start: true,
              end: false,
            }).test(currentPage.route)
          ) {
            // token无效
            clearLogout(res.data.respDesc);
          }
          break;
        default:
          break;
      }
    }
    return res.data;
  },
  (error) => {
    console.log('err' + error); // for debug
    switch (error.request.status) {
      case 401: // 无权限访问，需要登录
        return Promise.reject ? Promise.reject(error) : error;
      case 500: // 请求接口错误
        if (error.config.linkError) {
          //
        }
        uni.showToast({
          title: '系统服务崩溃啦',
          icon: 'error',
          duration: 3000,
        });
        return Promise.reject ? Promise.reject(error) : error;
    }
    return Promise.reject ? Promise.reject(error) : error;
  },
);
